//--------------------------------------------------------------------------------
// This file is a portion of the PracticeEngine Rendering Engine.  It is distributed
// under the MIT License, available in the root of this distribution and 
// at the following URL:
//
// http://www.opensource.org/licenses/mit-license.php
//
// Copyright (c) Ferdinand Li 
//--------------------------------------------------------------------------------
#include "RenderActor.h"
#include "Logger.h"
#include "ResourceManager.h"

using namespace PracEng;

RenderActor::RenderActor() :pVB(NULL)
{
	pSRV_ary[0] = nullptr;
	pSRV_ary[1] = nullptr;
}

RenderActor::~RenderActor()
{

}
void RenderActor::SetDiffuseTex(const wchar_t* Src, DX11Renderer* Dx11Render)
{
	UINT fmt = 0;
	if (wcsstr(Src, TEXT("vase_plant.bmp")) != NULL || wcsstr(Src, TEXT("chain_texture.bmp")) != NULL || wcsstr(Src, TEXT("sponza_thorn_diff")) != NULL)
	{
		fmt = DXGI_FORMAT_B8G8R8A8_UNORM;
	}
	GResourceMgr.GetTexture(Src, Dx11Render, &pSRV_ary[0], fmt);
}

void RenderActor::SetNormalTex(const wchar_t* Src, DX11Renderer* Dx11Render)
{
	GResourceMgr.GetTexture(Src, Dx11Render, &pSRV_ary[1]);
}

void RenderActor::CreateVertexBuffer(DX11Renderer* Dx11Render)
{
	HRESULT hr = S_OK;
	D3D11_BUFFER_DESC bufferDesc;
	UINT stride = sizeof(VertexLayOut_OBJ);
	ZeroMemory(&bufferDesc, sizeof(bufferDesc));
	bufferDesc.Usage = D3D11_USAGE_DEFAULT;
	bufferDesc.ByteWidth = stride * VertexBuffer.size();
	bufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
	bufferDesc.CPUAccessFlags = 0;
	bufferDesc.MiscFlags = 0;
	D3D11_SUBRESOURCE_DATA InitData;
	ZeroMemory(&InitData, sizeof(InitData));
	InitData.pSysMem = &VertexBuffer[0];
	hr = Dx11Render->GetDevice()->CreateBuffer(&bufferDesc, &InitData, &pVB);
	if (hr == E_FAIL)
	{
		PracEngLogf("Model: %s create vertex buffer faild! \n", Name.c_str());
	}
}

void PracEng::RenderActor::Draw(DX11Renderer* Dx11Render)
{
	UINT stride = sizeof(VertexLayOut_OBJ);
	UINT offset = 0;

	Dx11Render->GetDeviceContext()->IASetVertexBuffers(0, 1, &pVB, &stride, &offset);
	if (pSRV_ary[0] != nullptr)
		Dx11Render->GetDeviceContext()->PSSetShaderResources(0, 2, pSRV_ary);
	Dx11Render->GetDeviceContext()->Draw(VertexBuffer.size(), 0);
}


